package JUC;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Producter_Consumer_Lock {

    public static void main(String[] args) {
        Data data = new Data();
        new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                data.increment();
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                data.decrement();
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                data.increment();
            }
        }, "C").start();
        new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                data.decrement();
            }
        }, "D").start();

    }
}

class Data {
    private int i = 0;
    Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void decrement() {
        lock.lock();
        try {
            while (i == 0) {
                condition.await();
            }
            i--;
            System.out.println(Thread.currentThread().getName() + "减少了1，现在i为" + i);
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();

        }
    }

    public void increment() {
        lock.lock();
        try {
            while (i == 1) {
                condition.await();
            }
            i++;
            System.out.println(Thread.currentThread().getName() + "增加了1，现在i为" + i);
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();

        }
    }
}
